/*
 * FreeRTOS Kernel V10.2.0
 * Copyright (C) 2017 Amazon.com, Inc. or its affiliates.  All Rights Reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * http://www.FreeRTOS.org
 * http://aws.amazon.com/freertos
 *
 * 1 tab == 4 spaces!
 */

/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"

#include <stdio.h>
#include <string.h>

/* FreeRTOS+CLI includes. */
#include "FreeRTOS_CLI.h"


/*
 * Defines a command that returns a table showing the state of each task at the
 * time the command is called.
 */
static BaseType_t prvTaskStatsCommand(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);

/*
 * Defines a command that returns a table showing how much time each task has
 * spent in the Running state.
 */
static BaseType_t prvRunTimeStatsCommand(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);

/*
 * Defines a command that expects exactly three parameters.  Each of the three
 * parameter are echoed back one at a time.
 */
static BaseType_t prvThreeParameterEchoCommand(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);

/*
 * Defines a command that can take a variable number of parameters.  Each
 * parameter is echoes back one at a time.
 */
static BaseType_t prvParameterEchoCommand(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);


static BaseType_t prvListFileCommand(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString);

/* Structure that defines the "run-time-stats" command line command. */
static const CLI_Command_Definition_t xRunTimeStats =
{
    "run-time-stats",                                                                                                                /* The command string to type. */
    "run-time-stats:\r\n Displays a table showing how much processing time each FreeRTOS task has used\r\n", prvRunTimeStatsCommand, /* The function to run. */
    0                                                                                                                                /* No parameters are expected. */
};

/* Structure that defines the "task-stats" command line command. */
static const CLI_Command_Definition_t xTaskStats =
{
    "task-stats",                                                                                        /* The command string to type. */
    "task-stats:\r\n Displays a table showing the state of each FreeRTOS task\r\n", prvTaskStatsCommand, /* The function to run. */
    0                                                                                                    /* No parameters are expected. */
};

/* Structure that defines the "echo_3_parameters" command line command.  This
takes exactly three parameters that the command simply echos back one at a
time. */
static const CLI_Command_Definition_t xThreeParameterEcho =
{
    "echo_3_parameters", "echo_3_parameters <param1> <param2> <param3>:\r\n Expects three parameters, echos each in turn\r\n", prvThreeParameterEchoCommand, /* The function to run. */
    3 /* Three parameters are expected, which can take any value. */
};

/* Structure that defines the "echo_parameters" command line command.  This
takes a variable number of parameters that the command simply echos back one at
a time. */
static const CLI_Command_Definition_t xParameterEcho =
{
    "echo_parameters", "echo_parameters <...>:\r\n Take variable number of parameters, echos each in turn\r\n", prvParameterEchoCommand, /* The function to run. */
    -1                                                                                                                                   /* The user can enter any number of commands. */
};



static const CLI_Command_Definition_t xlistfiles =
{
    "ls",
    "ls:\r\n List file on root dir\r\n",
    prvListFileCommand,
    0                                                                                                   
};


/*-----------------------------------------------------------*/

void vRegisterCLICommands(void)
{
    /* Register all the command line commands defined immediately above. */
    FreeRTOS_CLIRegisterCommand(&xTaskStats);
    FreeRTOS_CLIRegisterCommand(&xRunTimeStats);
    FreeRTOS_CLIRegisterCommand(&xThreeParameterEcho);
    FreeRTOS_CLIRegisterCommand(&xParameterEcho);
    FreeRTOS_CLIRegisterCommand(&xlistfiles);
}
/*-----------------------------------------------------------*/

static BaseType_t prvTaskStatsCommand(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
{
    const char *const pcHeader = "Task          State  Priority  Stack	#\r\n************************************************\r\n";

    /* Remove compile time warnings about unused parameters, and check the
    write buffer is not NULL.  NOTE - for simplicity, this example assumes the
    write buffer length is adequate, so does not check for buffer overflows. */
    (void)pcCommandString;
    (void)xWriteBufferLen;
    configASSERT(pcWriteBuffer);

    /* Generate a table of task stats. */
    strcpy(pcWriteBuffer, pcHeader);
    vTaskList(pcWriteBuffer + strlen(pcHeader));

    /* There is no more data to return after this single string, so return
    pdFALSE. */
    return pdFALSE;
}
/*-----------------------------------------------------------*/

static BaseType_t prvRunTimeStatsCommand(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
{
    const char *const pcHeader = "Task            Abs Time      % Time\r\n****************************************\r\n";

    /* Remove compile time warnings about unused parameters, and check the
    write buffer is not NULL.  NOTE - for simplicity, this example assumes the
    write buffer length is adequate, so does not check for buffer overflows. */
    (void)pcCommandString;
    (void)xWriteBufferLen;
    configASSERT(pcWriteBuffer);

    /* Generate a table of task stats. */
    strcpy(pcWriteBuffer, pcHeader);
    // vTaskGetRunTimeStats( pcWriteBuffer + strlen( pcHeader ) );

    /* There is no more data to return after this single string, so return
    pdFALSE. */
    return pdFALSE;
}
/*-----------------------------------------------------------*/

static BaseType_t prvThreeParameterEchoCommand(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
{
    const char       *pcParameter;
    BaseType_t        lParameterStringLength, xReturn;
    static BaseType_t lParameterNumber = 0;

    /* Remove compile time warnings about unused parameters, and check the
    write buffer is not NULL.  NOTE - for simplicity, this example assumes the
    write buffer length is adequate, so does not check for buffer overflows. */
    (void)pcCommandString;
    (void)xWriteBufferLen;
    configASSERT(pcWriteBuffer);

    if(lParameterNumber == 0)
    {
        /* The first time the function is called after the command has been
        entered just a header string is returned. */
        sprintf(pcWriteBuffer, "The three parameters were:\r\n");

        /* Next time the function is called the first parameter will be echoed
        back. */
        lParameterNumber = 1L;

        /* There is more data to be returned as no parameters have been echoed
        back yet. */
        xReturn = pdPASS;
    }
    else
    {
        /* Obtain the parameter string. */
        pcParameter = FreeRTOS_CLIGetParameter(pcCommandString,        /* The command string itself. */
                                               lParameterNumber,       /* Return the next parameter. */
                                               &lParameterStringLength /* Store the parameter string length. */
                                              );

        /* Sanity check something was returned. */
        configASSERT(pcParameter);

        /* Return the parameter string. */
        memset(pcWriteBuffer, 0x00, xWriteBufferLen);
        sprintf(pcWriteBuffer, "%d: ", lParameterNumber);
        strncat(pcWriteBuffer, pcParameter, lParameterStringLength);
        strncat(pcWriteBuffer, "\r\n", strlen("\r\n"));

        /* If this is the last of the three parameters then there are no more
        strings to return after this one. */
        if(lParameterNumber == 3L)
        {
            /* If this is the last of the three parameters then there are no more
            strings to return after this one. */
            xReturn          = pdFALSE;
            lParameterNumber = 0L;
        }
        else
        {
            /* There are more parameters to return after this one. */
            xReturn = pdTRUE;
            lParameterNumber++;
        }
    }

    return xReturn;
}
/*-----------------------------------------------------------*/

static BaseType_t prvParameterEchoCommand(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
{
    const char       *pcParameter;
    BaseType_t        lParameterStringLength, xReturn;
    static BaseType_t lParameterNumber = 0;

    /* Remove compile time warnings about unused parameters, and check the
    write buffer is not NULL.  NOTE - for simplicity, this example assumes the
    write buffer length is adequate, so does not check for buffer overflows. */
    (void)pcCommandString;
    (void)xWriteBufferLen;
    configASSERT(pcWriteBuffer);

    if(lParameterNumber == 0)
    {
        /* The first time the function is called after the command has been
        entered just a header string is returned. */
        sprintf(pcWriteBuffer, "The parameters were:\r\n");

        /* Next time the function is called the first parameter will be echoed
        back. */
        lParameterNumber = 1L;

        /* There is more data to be returned as no parameters have been echoed
        back yet. */
        xReturn = pdPASS;
    }
    else
    {
        /* Obtain the parameter string. */
        pcParameter = FreeRTOS_CLIGetParameter(pcCommandString,        /* The command string itself. */
                                               lParameterNumber,       /* Return the next parameter. */
                                               &lParameterStringLength /* Store the parameter string length. */
                                              );

        if(pcParameter != NULL)
        {
            /* Return the parameter string. */
            memset(pcWriteBuffer, 0x00, xWriteBufferLen);
            sprintf(pcWriteBuffer, "%d: ", lParameterNumber);
            strncat(pcWriteBuffer, pcParameter, lParameterStringLength);
            strncat(pcWriteBuffer, "\r\n", strlen("\r\n"));

            /* There might be more parameters to return after this one. */
            xReturn = pdTRUE;
            lParameterNumber++;
        }
        else
        {
            /* No more parameters were found.  Make sure the write buffer does
            not contain a valid string. */
            pcWriteBuffer[0] = 0x00;

            /* No more data to return. */
            xReturn = pdFALSE;

            /* Start over the next time this command is executed. */
            lParameterNumber = 0;
        }
    }

    return xReturn;
}
/*-----------------------------------------------------------*/


#include "ff.h"
static FRESULT scan_files(char *path, char *writeBuf)
{
    FRESULT res;
    DIR dir;
    UINT i;
    static FILINFO fno;


    res = f_opendir(&dir, path);                       /* Open the directory */

    if(res == FR_OK)
    {
        for(;;)
        {
            res = f_readdir(&dir, &fno);                   /* Read a directory item */

            if(res != FR_OK || fno.fname[0] == 0)
            {
                break;    /* Break on error or end of dir */
            }

            if(fno.fattrib & AM_DIR)                       /* It is a directory */
            {
                //i = strlen(path);
                sprintf(path, "/%s", fno.fname);
                res = scan_files(path, writeBuf + strlen(fno.fname) + strlen("\r\n"));                /* Enter the directory */

                if(res != FR_OK)
                {
                    break;
                }

                path[i] = 0;
            }
            else                                           /* It is a file. */
            {
                strcpy(writeBuf, fno.fname);
                strcpy(writeBuf + strlen(fno.fname), "\r\n");
                //LOG("%s%s\n", path, fno.fname);
            }
        }

        f_closedir(&dir);
    }

    return res;
}


static BaseType_t prvListFileCommand(char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString)
{
    const char *const pcHeader = "List file\r\n****************************************\r\n";

    (void)pcCommandString;
    (void)xWriteBufferLen;
    configASSERT(pcWriteBuffer);

    /* Generate a table of task stats. */
    strcpy(pcWriteBuffer, pcHeader);
    strlen(pcHeader);

    scan_files("/", pcWriteBuffer + strlen(pcHeader));

    // vTaskGetRunTimeStats( pcWriteBuffer + strlen( pcHeader ) );

    /* There is no more data to return after this single string, so return
    pdFALSE. */
    return pdFALSE;
}
/*-----------------------------------------------------------*/
